package com.pdstudio.carrecom.ui.activity.myclub;

import java.util.ArrayList;
import java.util.List;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.lidroid.xutils.http.RequestParams;
import com.pdstudio.carrecom.R;
import com.pdstudio.carrecom.api.HttpExecuteJson;
import com.pdstudio.carrecom.api.ServiceHelper;
import com.pdstudio.carrecom.api.HttpExecuteJson.httpReturnJson;
import com.pdstudio.carrecom.app.UIHelper;
import com.pdstudio.carrecom.bean.BehindPerson;
import com.pdstudio.carrecom.bean.PhoneValideCode;
import com.pdstudio.carrecom.tools.StringUtils;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;

/**
 * 我附近的人 类: ActivityBehind <br>
 * 描述: TODO <br>
 * 作者: xiangzhaoyu <br>
 * 时间: 2015-6-24 下午9:27:03
 */
public class ActivityBehind extends Activity {

	private View customLiveIndexTitleView;
	private TextView txtTitle;
	private ImageView ivBack;

	// 定位相关
	LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
	private LocationMode mCurrentMode;
	BitmapDescriptor mCurrentMarker;

	MapView mMapView;
	BaiduMap mBaiduMap;

	// UI相关
	OnCheckedChangeListener radioButtonListener;
	Button requestLocButton;
	boolean isFirstLoc = true;// 是否首次定位

	private LinearLayout mSendInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_myclub_behind);

		initTitle();
		InitialView();
	}

	private void initTitle() {
		txtTitle = (TextView) findViewById(R.id.title_text_nav);

		txtTitle.setText("附近的人");

		ivBack = (ImageView) findViewById(R.id.title_back);
		ivBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void InitialView() {

		mSendInfo = (LinearLayout) findViewById(R.id.ll_behind_sendinfo);

		// 地图初始化
		mMapView = (MapView) findViewById(R.id.baidu_map_behind);
		mBaiduMap = mMapView.getMap();

		// 设定中心点坐标

		LatLng cenpt = new LatLng(29.36063, 113.09578);
		// 定义地图状态
		MapStatus mMapStatus = new MapStatus.Builder().target(cenpt).zoom(9)
				.build();
		// 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
		MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory
				.newMapStatus(mMapStatus);
		// 改变地图状态
		mBaiduMap.setMapStatus(mMapStatusUpdate);

		try {
			HttpExecuteJson http = new HttpExecuteJson(this,
					mGetBehindPersonListener);
			RequestParams rps = new RequestParams();
			rps.addBodyParameter("carname", "");
			rps.addBodyParameter("passwd", "");
			rps.addBodyParameter("name", "");
			rps.addBodyParameter("phone", "");
			http.post(ServiceHelper.GetBehindPersons, rps);
		} catch (Exception e) {
			e.printStackTrace();
			UIHelper.ToastMessage(this, "获取附近的人失败：" + e.getMessage());
		}
	}

	private httpReturnJson mGetBehindPersonListener = new httpReturnJson() {
		@Override
		public void onFailure(int error, String msg) {
			UIHelper.ToastMessage(ActivityBehind.this, "获取附近的人失败" + msg);
		}

		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			UIHelper.ToastMessage(ActivityBehind.this, "获取附近的人失败");
		}

		// 获取到饲料配方类型成功
		public void onSuccess(String result) {
			// TODO Auto-generated method stub
			// UIHelper.ToastMessage(_context,"总条数=" + result + "");
			DoJsonBp(result);
		}
	};

	private void DoJsonBp(String json) {
		PhoneValideCode edv = null;
		try {
			edv = new Gson().fromJson(json, new TypeToken<PhoneValideCode>() {
			}.getType());
			if ((edv != null)
					&& (edv.msg.equals(ServiceHelper.msg_code_sucess))) {
				// 原本在initview的代码放在这下面
				try {

					List<BehindPerson> bps = new ArrayList<BehindPerson>();
					SetBehindPersonsAdapter(bps);

				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				UIHelper.ToastMessage(ActivityBehind.this, "获取附近的人失败");

			}
		} catch (Exception e) {
			e.printStackTrace();
			UIHelper.ToastMessage(ActivityBehind.this,
					"获取附近的人失败" + e.getMessage());
		}

	}

	private void SetBehindPersonsAdapter(List<BehindPerson> si) {
		if (si != null) {
			for (int i = 0; i < si.size(); i++) {
				try {
					BehindPerson ss = new BehindPerson();
					ss.pId = si.get(i).pId;
					ss.lat = si.get(i).lat;
					ss.lon = si.get(i).lon;

					double latd = 0;
					double lond = 0;
					try {
						latd = Double.valueOf(ss.lat);
						lond = Double.valueOf(ss.lon);
					} catch (Exception e) {
						e.printStackTrace();
					}

					// 定义Maker坐标点
					LatLng point = new LatLng(latd, lond);
					// 构建Marker图标
					BitmapDescriptor bitmap = BitmapDescriptorFactory
							.fromResource(R.drawable.checked);
					// 构建MarkerOption，用于在地图上添加Marker
					OverlayOptions option = new MarkerOptions().position(point)
							.rotate(0).icon(bitmap);
					// 在地图上添加Marker，并显示
					// 将marker添加到地图上
					Marker marker = (Marker) (mBaiduMap.addOverlay(option));
					// 将信息写入marker
					Bundle bundle = new Bundle();
					bundle.putSerializable("info", ss);
					marker.setExtraInfo(bundle);

					// 添加标志物弹出框
					mBaiduMap
							.setOnMarkerClickListener(new OnMarkerClickListener() {
								@Override
								public boolean onMarkerClick(final Marker marker) {
									// 获得marker中的数据
									BehindPerson info = (BehindPerson) marker
											.getExtraInfo().get("info");

									mSendInfo.setVisibility(View.VISIBLE);
									return true;
								}
							});

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null)
				return;
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);
			if (isFirstLoc) {
				isFirstLoc = false;
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				mBaiduMap.animateMapStatus(u);
			}
		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}

	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		try {
			// 退出时销毁定位
			mLocClient.stop();
			// 关闭定位图层
			mBaiduMap.setMyLocationEnabled(false);
			mMapView.onDestroy();
			mMapView = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

}
